import 'package:sqflite/sqflite.dart';
import 'package:logger/logger.dart';
import '../core/database_helper.dart';
import '../models/carbon_footprint_record.dart';

/// 碳足迹记录服务类
class CarbonFootprintService {
  static final CarbonFootprintService _instance = CarbonFootprintService._internal();
  final Logger _logger = Logger();

  factory CarbonFootprintService() {
    return _instance;
  }

  CarbonFootprintService._internal();

  /// 获取数据库实例
  Future<Database> get _database async {
    return await DatabaseHelper().database;
  }

  /// 生成记录编号
  String _generateRecordCode() {
    final now = DateTime.now();
    final dateStr = '${now.year}${now.month.toString().padLeft(2, '0')}${now.day.toString().padLeft(2, '0')}';
    final timeStr = '${now.hour.toString().padLeft(2, '0')}${now.minute.toString().padLeft(2, '0')}${now.second.toString().padLeft(2, '0')}';
    final millisecondStr = now.millisecond.toString().padLeft(3, '0');
    return 'CFP-$dateStr-$timeStr-$millisecondStr';
  }

  /// 获取所有碳足迹记录
  Future<List<CarbonFootprintRecord>> getAllRecords({
    int? limit,
    int? offset,
    String? searchKeyword,
    int? processType,
    DateTime? startDate,
    DateTime? endDate,
  }) async {
    _logger.d('🔍 开始获取碳足迹记录');
    
    try {
      final db = await _database;
      
      // 构建查询条件
      final List<String> whereConditions = ['is_deleted = 0'];
      final List<dynamic> whereArgs = [];
      
      if (searchKeyword != null && searchKeyword.isNotEmpty) {
        whereConditions.add('(record_name LIKE ? OR record_code LIKE ? OR location LIKE ?)');
        final keyword = '%$searchKeyword%';
        whereArgs.addAll([keyword, keyword, keyword]);
      }
      
      if (processType != null) {
        whereConditions.add('process_type = ?');
        whereArgs.add(processType);
      }
      
      if (startDate != null) {
        whereConditions.add('record_date >= ?');
        whereArgs.add(startDate.toIso8601String().split('T')[0]);
      }
      
      if (endDate != null) {
        whereConditions.add('record_date <= ?');
        whereArgs.add(endDate.toIso8601String().split('T')[0]);
      }
      
      final whereClause = whereConditions.join(' AND ');
      
      // 执行查询
      final List<Map<String, dynamic>> maps = await db.query(
        'carbon_footprint_records',
        where: whereClause,
        whereArgs: whereArgs,
        orderBy: 'created_at DESC',
        limit: limit,
        offset: offset,
      );
      
      final records = maps.map((map) => CarbonFootprintRecord.fromMap(map)).toList();
      
      _logger.i('✅ 获取碳足迹记录成功: ${records.length} 条记录');
      return records;
    } catch (e) {
      _logger.e('❌ 获取碳足迹记录失败: $e');
      rethrow;
    }
  }

  /// 根据ID获取碳足迹记录
  Future<CarbonFootprintRecord?> getRecordById(int id) async {
    _logger.d('🔍 开始获取碳足迹记录: id=$id');
    
    try {
      final db = await _database;
      
      final List<Map<String, dynamic>> maps = await db.query(
        'carbon_footprint_records',
        where: 'id = ? AND is_deleted = 0',
        whereArgs: [id],
      );
      
      if (maps.isNotEmpty) {
        final record = CarbonFootprintRecord.fromMap(maps.first);
        _logger.i('✅ 获取碳足迹记录成功: ${record.recordName}');
        return record;
      } else {
        _logger.w('⚠️ 未找到碳足迹记录: id=$id');
        return null;
      }
    } catch (e) {
      _logger.e('❌ 获取碳足迹记录失败: $e');
      rethrow;
    }
  }

  /// 根据记录编号获取碳足迹记录
  Future<CarbonFootprintRecord?> getRecordByCode(String recordCode) async {
    _logger.d('🔍 开始获取碳足迹记录: recordCode=$recordCode');
    
    try {
      final db = await _database;
      
      final List<Map<String, dynamic>> maps = await db.query(
        'carbon_footprint_records',
        where: 'record_code = ? AND is_deleted = 0',
        whereArgs: [recordCode],
      );
      
      if (maps.isNotEmpty) {
        final record = CarbonFootprintRecord.fromMap(maps.first);
        _logger.i('✅ 获取碳足迹记录成功: ${record.recordName}');
        return record;
      } else {
        _logger.w('⚠️ 未找到碳足迹记录: recordCode=$recordCode');
        return null;
      }
    } catch (e) {
      _logger.e('❌ 获取碳足迹记录失败: $e');
      rethrow;
    }
  }

  /// 创建碳足迹记录
  Future<CarbonFootprintRecord> createRecord(CarbonFootprintRecord record) async {
    _logger.d('💾 开始创建碳足迹记录: ${record.recordName}');
    
    try {
      final db = await _database;
      
      // 生成记录编号
      final recordCode = _generateRecordCode();
      final now = DateTime.now();
      
      final newRecord = record.copyWith(
        recordCode: recordCode,
        createdAt: now,
        updatedAt: now,
        isDeleted: false,
      );
      
      final id = await db.insert('carbon_footprint_records', newRecord.toMap());
      
      final createdRecord = newRecord.copyWith(id: id);
      
      _logger.i('✅ 碳足迹记录创建成功: ${createdRecord.recordName}, id=$id');
      return createdRecord;
    } catch (e) {
      _logger.e('❌ 创建碳足迹记录失败: $e');
      rethrow;
    }
  }

  /// 更新碳足迹记录
  Future<bool> updateRecord(CarbonFootprintRecord record) async {
    _logger.d('💾 开始更新碳足迹记录: ${record.recordName}, id=${record.id}');
    
    try {
      final db = await _database;
      
      final updatedRecord = record.copyWith(
        updatedAt: DateTime.now(),
      );
      
      final count = await db.update(
        'carbon_footprint_records',
        updatedRecord.toMap(),
        where: 'id = ? AND is_deleted = 0',
        whereArgs: [record.id],
      );
      
      if (count > 0) {
        _logger.i('✅ 碳足迹记录更新成功: ${record.recordName}');
        return true;
      } else {
        _logger.w('⚠️ 碳足迹记录更新失败: 未找到记录或记录已删除');
        return false;
      }
    } catch (e) {
      _logger.e('❌ 更新碳足迹记录失败: $e');
      rethrow;
    }
  }

  /// 删除碳足迹记录（软删除）
  Future<bool> deleteRecord(int id) async {
    _logger.d('🗑️ 开始删除碳足迹记录: id=$id');
    
    try {
      final db = await _database;
      
      final count = await db.update(
        'carbon_footprint_records',
        {
          'is_deleted': 1,
          'updated_at': DateTime.now().toIso8601String(),
        },
        where: 'id = ? AND is_deleted = 0',
        whereArgs: [id],
      );
      
      if (count > 0) {
        _logger.i('✅ 碳足迹记录删除成功: id=$id');
        return true;
      } else {
        _logger.w('⚠️ 碳足迹记录删除失败: 未找到记录或记录已删除');
        return false;
      }
    } catch (e) {
      _logger.e('❌ 删除碳足迹记录失败: $e');
      rethrow;
    }
  }

  /// 搜索碳足迹记录
  Future<List<CarbonFootprintRecord>> searchRecords(String keyword) async {
    _logger.d('🔍 开始搜索碳足迹记录: keyword=$keyword');
    
    try {
      final db = await _database;
      
      final List<Map<String, dynamic>> maps = await db.query(
        'carbon_footprint_records',
        where: 'is_deleted = 0 AND (record_name LIKE ? OR record_code LIKE ? OR location LIKE ? OR description LIKE ?)',
        whereArgs: ['%$keyword%', '%$keyword%', '%$keyword%', '%$keyword%'],
        orderBy: 'created_at DESC',
      );
      
      final records = maps.map((map) => CarbonFootprintRecord.fromMap(map)).toList();
      
      _logger.i('✅ 搜索碳足迹记录成功: 找到 ${records.length} 条记录');
      return records;
    } catch (e) {
      _logger.e('❌ 搜索碳足迹记录失败: $e');
      rethrow;
    }
  }

  /// 获取工艺类型列表
  Future<List<Map<String, dynamic>>> getProcessTypes() async {
    _logger.d('🔍 开始获取工艺类型列表');
    
    try {
      final db = await _database;
      
      final List<Map<String, dynamic>> maps = await db.query(
        'process_types',
        where: 'is_active = 1',
        orderBy: 'id ASC',
      );
      
      _logger.i('✅ 获取工艺类型列表成功: ${maps.length} 种工艺');
      return maps;
    } catch (e) {
      _logger.e('❌ 获取工艺类型列表失败: $e');
      rethrow;
    }
  }

  /// 获取统计信息
  Future<Map<String, dynamic>> getStatistics({
    DateTime? startDate,
    DateTime? endDate,
    int? processType,
  }) async {
    _logger.d('📊 开始获取统计信息');
    
    try {
      final db = await _database;
      
      // 构建查询条件
      final List<String> whereConditions = ['is_deleted = 0'];
      final List<dynamic> whereArgs = [];
      
      if (startDate != null) {
        whereConditions.add('record_date >= ?');
        whereArgs.add(startDate.toIso8601String().split('T')[0]);
      }
      
      if (endDate != null) {
        whereConditions.add('record_date <= ?');
        whereArgs.add(endDate.toIso8601String().split('T')[0]);
      }
      
      if (processType != null) {
        whereConditions.add('process_type = ?');
        whereArgs.add(processType);
      }
      
      final whereClause = whereConditions.join(' AND ');
      
      // 获取基础统计
      final List<Map<String, dynamic>> stats = await db.rawQuery('''
        SELECT 
          COUNT(*) as total_records,
          COALESCE(SUM(production_capacity), 0) as total_production,
          COALESCE(SUM(energy_consumption), 0) as total_energy_consumption,
          COALESCE(SUM(carbon_emission), 0) as total_carbon_emission,
          COALESCE(AVG(CASE WHEN production_capacity > 0 THEN carbon_emission / production_capacity ELSE 0 END), 0) as avg_emission_intensity,
          COALESCE(AVG(CASE WHEN production_capacity > 0 THEN energy_consumption / production_capacity ELSE 0 END), 0) as avg_energy_intensity
        FROM carbon_footprint_records 
        WHERE $whereClause
      ''', whereArgs);
      
      // 按工艺类型统计
      final List<Map<String, dynamic>> processStats = await db.rawQuery('''
        SELECT 
          process_type,
          COUNT(*) as record_count,
          COALESCE(SUM(production_capacity), 0) as production_volume,
          COALESCE(SUM(energy_consumption), 0) as energy_consumption,
          COALESCE(SUM(carbon_emission), 0) as carbon_emission
        FROM carbon_footprint_records 
        WHERE $whereClause
        GROUP BY process_type
        ORDER BY process_type
      ''', whereArgs);
      
      final result = {
        'total_records': stats.first['total_records'] ?? 0,
        'total_production': (stats.first['total_production'] ?? 0).toDouble(),
        'total_energy_consumption': (stats.first['total_energy_consumption'] ?? 0).toDouble(),
        'total_carbon_emission': (stats.first['total_carbon_emission'] ?? 0).toDouble(),
        'avg_emission_intensity': (stats.first['avg_emission_intensity'] ?? 0).toDouble(),
        'avg_energy_intensity': (stats.first['avg_energy_intensity'] ?? 0).toDouble(),
        'process_statistics': processStats,
      };
      
      _logger.i('✅ 获取统计信息成功');
      return result;
    } catch (e) {
      _logger.e('❌ 获取统计信息失败: $e');
      rethrow;
    }
  }

  /// 验证记录数据
  static Map<String, String?> validateRecordData({
    required String recordName,
    required int processType,
    required double productionCapacity,
    required double energyConsumption,
    required double carbonEmission,
    String? energySource,
    double? equipmentEfficiency,
    int? operationHours,
    String? location,
    String? projectPhase,
  }) {
    final errors = <String, String?>{};
    
    // 验证记录名称
    errors['recordName'] = CarbonFootprintRecord.validateRecordName(recordName);
    
    // 验证工艺类型
    errors['processType'] = CarbonFootprintRecord.validateProcessType(processType);
    
    // 验证产能
    errors['productionCapacity'] = CarbonFootprintRecord.validateProductionCapacity(productionCapacity.toString());
    
    // 验证能耗
    errors['energyConsumption'] = CarbonFootprintRecord.validateEnergyConsumption(energyConsumption.toString());
    
    // 验证碳排放量
    errors['carbonEmission'] = CarbonFootprintRecord.validateCarbonEmission(carbonEmission.toString());
    
    // 验证设备效率
    if (equipmentEfficiency != null) {
      errors['equipmentEfficiency'] = CarbonFootprintRecord.validateEquipmentEfficiency(equipmentEfficiency.toString());
    }
    
    // 验证运行时间
    if (operationHours != null) {
      errors['operationHours'] = CarbonFootprintRecord.validateOperationHours(operationHours.toString());
    }
    
    // 验证地理位置
    if (location != null) {
      errors['location'] = CarbonFootprintRecord.validateLocation(location);
    }
    
    // 验证项目阶段
    if (projectPhase != null) {
      errors['projectPhase'] = CarbonFootprintRecord.validateProjectPhase(projectPhase);
    }
    
    return errors;
  }
} 